<template>
    <div id="app">
        <h1>简单的聊天应用程序</h1>
        <div class="chat-box">
            <div class="messages" ref="messages">
            </div>
            <div class="input-area">
                <input type="text" v-model="input" @keyup.enter="sendMessage" placeholder="输入消息并按回车键发送" />
            </div>
        </div>
    </div>
</template>

<script>
    import axios from "axios";
    export default {
        name: "Chat",
        data() {
            return {
                input: "",
                messages:"",
                eventSource: null,
            };
        },
        mounted() {
            this.initSSE();
        },
        beforeDestroy() {
            this.eventSource.close();
        },
        methods: {
            initSSE() {
                // 创建一个SSE对象，连接到后端的/chat接口
                this.eventSource = new EventSource("http://localhost:8081/chat");
                // 监听message事件，接收后端发送的消息
                this.eventSource.addEventListener("message", (event) => {
                    //将返回data插入元素
                    this.$refs.messages.innerHTML+= event.data
                });
            },
        },
    };
</script>

<style>
    * {
        box-sizing: border-box;
        margin: 0;
        padding: 0;
    }
    h1 {
        text-align: center;
    }
    .chat-box {
        width: 600px;
        height: 400px;
        margin: 20px auto;
        border: 1px solid #ccc;
    }
    .messages {
        height: 360px;
        overflow-y: auto;
        text-align: left;
    }
    .message {
        padding: 10px;
    }
    .message.user {
        text-align: right;
    }
    .message.user .content {
        display: inline-block;
        background-color: #f0f0f0;
        border-radius: 10px;
    }
    .message.user .time {
        display: block;
        color: #999;
    }
    .message.bing {
        text-align: left;
    }
    .message.bing .content {
        display: inline-block;
        background-color: #e6f7ff;
        border-radius: 10px;
    }
    .message.bing .time {
        display: block;
        color: #999;
    }
    .input-area {
        height: 40px;
    }
    .input-area input {
        width: calc(100% - 20px);
        height: calc(100% - 10px);
        margin: 5px auto;
    }
</style>

